/*
 * @Description: 辅助
 * @Author: HuiSir<273250950@qq.com>
 * @Date: 2022-02-09 14:54:22
 * @LastEditTime: 2025-08-14 09:59:31
 */
import Mock from "mockjs";
import { MockMethod } from "vite-plugin-mock";
import { loadEnv } from "vite";
import { ProjectConfig } from "../init/types";
import jsYaml from "js-yaml";
import fs from "node:fs";
/* eslint-disable @typescript-eslint/no-explicit-any */

/**
 * 取项目配置
 */
export const useProjectConfig = () => {
  // 当前文件是在编译时执行的，所以这里使用js-yaml去读取配置
  // 若使用直接导入yaml文件则会报错
  return jsYaml.load(
    fs.readFileSync("./project-config.yaml", "utf8")
  ) as ProjectConfig;
};

/**
 * DOC:https://github.com/nuysoft/Mock/wiki
 * Examples:http://mockjs.com/examples.html
 * https://gitee.com/wangchao2203/vite-plugin-mock
 */

export const rules2MockMethods = (
  rules: Record<string, any>,
  prefix: string
) => {
  // 配置项
  const project = useProjectConfig();

  // 只有开发时候使用mock，所以这里直接配置环境mode为dev
  const BaseApi = loadEnv("dev", process.cwd()).VITE_BASE_API;
  const MockMethods: MockMethod[] = [];
  Object.keys(rules).forEach((key) => {
    MockMethods.push({
      url: BaseApi + prefix + key,
      timeout: Math.floor(Math.random() * 100),
      rawResponse(req, res) {
        // 响应头(模拟登陆接口返回token)
        if (req.url?.includes("/login")) {
          res.setHeader(project.token.key, "dev-mock-token");
        }

        // 解决中文乱码
        res.setHeader("Content-Type", "application/json; charset=utf-8");

        res.statusCode = 200;

        const data = Mock.mock({
          ok: 1,
          [project.responseFields.message]: "成功",
          [project.responseFields.code]: project.responseBaseCode.success,
          ...rules[key],
        });

        res.end(JSON.stringify(data));
      },
    });
  });
  return MockMethods;
};

export function rawList2Tree({
  rawList,
  parentIdKey = "pid",
  childKey = "children",
}: {
  rawList: any[];
  parentIdKey?: string;
  childKey?: string;
}) {
  if (rawList.length === 0) {
    return [];
  }

  let treeList: any[] = [];

  (function Recursion(level: number = 0, pid?: string) {
    const tempArr: Record<string, string>[] = [];
    for (let index = 0; index < rawList.length; index++) {
      const item = rawList[index];
      // 如果没有父id（第一次递归的时候）将所有父级查询出来
      // 这里认为 !item[parentIdKey] 是最顶层
      if (pid ? item[parentIdKey] === pid : !item[parentIdKey]) {
        // 树层级标记
        item.treeLevel = level;
        // 通过父节点ID查询所有子节点
        item[childKey] = Recursion(level + 1, item.id);
        tempArr.push(item);
      }
    }
    if (!pid) {
      treeList = tempArr;
    }
    return tempArr;
  })();

  return treeList;
}
